package com.xhwl.centiotdata.suppliersystem.dnake;

import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.emq.dnake.DnakeMqttClient;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.centiotdata.utils.RedisUtils;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.pojo.ResultJson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;

import static com.xhwl.centiotdata.pojo.constant.DnakeConstant.*;

/**
 * @description:
 * @author: wuyuhao
 * @createDate: 2023/5/4 9:06
 */
@Service
@Slf4j
public class PedestrianDnakeHandler {

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private DnakeMqttClient dnakeMqttClient;

    public ResultJson openDoor(PedestrianIntegrationConfigDTO configDTO, DeviceDTO deviceDTO) {
        // 判断设备项目、在离线等信息
        String dtoThirdDeviceId = deviceDTO.getThirdDeviceId();
        String infoKey = String.format(DEVICE_INFO_REDIS_KEY, configDTO.getProjectId(), dtoThirdDeviceId);
        Set<String> infoKeys = redisUtils.getKeys(infoKey);
        if (infoKeys == null || infoKeys.isEmpty()) {
            log.error("{}项目不存在{}设备", configDTO.getProjectId(), dtoThirdDeviceId);
            return ResultJson.fail("该项目不存在此设备");
        }
        String onlineKey = String.format(DEVICE_ONLINE_REDIS_KEY, configDTO.getProjectId(), dtoThirdDeviceId);
        Set<String> onlineKeys = redisUtils.getKeys(onlineKey);
        if (onlineKeys == null || onlineKeys.isEmpty()) {
            log.error("设备{}不在线", dtoThirdDeviceId);
            return ResultJson.fail("该设备不在线");
        }
        String remoteOpenTopic = String.format(REMOTE_OPEN, dtoThirdDeviceId);
        JSONObject request = new JSONObject();
        request.put("msgId", "");
        request.put("from", FROM);
        request.put("action", "remoteOpen");
        request.put("params", new JSONObject());
        dnakeMqttClient.publish(remoteOpenTopic, request.toJSONString());
        return ResultJson.success();
    }

}
